package com.sushengren.easyword.constants;

import com.sushengren.easyword.converters.AutoConverter;
import com.sushengren.easyword.converters.Converter;
import com.sushengren.easyword.converters.ListConverter;
import com.sushengren.easyword.converters.StringConverter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认转换器
 *
 * @author sushengren
 */
public class DefaultConverters {

    private static final Map<String, Converter> DEFAULT_CONVERTERS = new ConcurrentHashMap<>();

    static {
        DEFAULT_CONVERTERS.put(AutoConverter.class.getName(), new AutoConverter());
        DEFAULT_CONVERTERS.put(StringConverter.class.getName(), new StringConverter());
        DEFAULT_CONVERTERS.put(ListConverter.class.getName(), new ListConverter());
    }

    public static Converter getConverter(String className) {
        Converter converter = DEFAULT_CONVERTERS.get(className);
        if (converter == null) {
            try {
                Class<?> clazz = Class.forName(className);
                Converter c = (Converter) clazz.newInstance();
                DEFAULT_CONVERTERS.put(className, c);
                return c;
            } catch (ClassNotFoundException e) {
                throw new IllegalArgumentException("找不到对应的转换器类", e);
            } catch (IllegalAccessException | InstantiationException e) {
                throw new IllegalArgumentException("转换器必须提供无参构造器", e);
            }
        }
        return converter;
    }

}
